package sii.dati;

import java.sql.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sii.commons.*;

public class Datasource {

    String host;
    int port;
    String schema;
    String user;
    String pass;

    private Connection connection;
    private Log log;
    private static Datasource instance;

    private Datasource(String host, int port, String schema, String user,
	    String pass) throws DataManagerException {
	this.host = host;
	this.port = port;
	this.schema = schema;
	this.user = user;
	this.pass = pass;
	this.log = LogFactory.getLog(Datasource.class);
	String db_uri;

	db_uri = "jdbc:mysql://" + host + ":" + port + "/" + schema
		+ "?allowMultiQuery=true";

	try {
	    Class.forName("com.mysql.jdbc.Driver");
	    connection = DriverManager.getConnection(db_uri, user, pass);

	} catch (Exception e) {
	    this.log.error("Errore durante la creazione del Datasource", e);
	    throw new DataManagerException(e);
	}
    }

    private Datasource() throws DataManagerException {
	try {
	    this.host = ConfigManager.get("db.host");
	    this.port = Integer.parseInt(ConfigManager.get("db.port"));
	    this.schema = ConfigManager.get("db.schema");
	    this.user = ConfigManager.get("db.username");
	    this.pass = ConfigManager.get("db.password");
	    this.log = LogFactory.getLog(Datasource.class);
	    String db_uri;

	    db_uri = "jdbc:mysql://" + host + ":" + port + "/" + schema
		    + "?allowMultiQuery=true";

	    // System.out.println(db_uri);
	    try {
		Class.forName("com.mysql.jdbc.Driver");
		connection = DriverManager.getConnection(db_uri, user, pass);

	    } catch (Exception e) {
		throw new DataManagerException(e);
	    }
	} catch (Exception e) {
	    this.log.error("Errore durante la creazione del Datasource", e);
	    throw new DataManagerException(e.getMessage());
	}

    }

    public Connection getConnection() {
	return connection;
    }

    public static Datasource getInstance() throws DataManagerException {
	if (instance == null) {
	    instance = new Datasource();
	}
	return instance;
    }

    public void close() throws DataManagerException {
	try {
	    connection.close();
	} catch (SQLException e) {
	    this.log.error("Errore durante la chiusura della connessioneS", e);
	    throw new DataManagerException(e.getMessage());
	}
    }
}
